using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;

namespace GraphEditor.Editor
{
    [InitializeOnLoad] // 让这个类在Unity编辑器启动时自动运行
    public static class GraphEditorRegistry
    {
        private static Dictionary<string, Type> _editorTypes;

        static GraphEditorRegistry()
        {
            _editorTypes = new Dictionary<string, Type>();

            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

            // 使用反射查找所有继承自 BaseGraphEditor 的类
            foreach (Assembly assembly in assemblies)
            {
                Type[] types = assembly.GetTypes();
                foreach (Type type in types)
                {
                    if (type.IsSubclassOf(typeof(BaseGraphEditor)))
                    {
                        CustomGraphEditorAttribute attr = type.GetCustomAttribute<CustomGraphEditorAttribute>();
                        if (attr != null)
                        {
                            Type graphType = attr.GraphType;
                            string graphTypeFullName = graphType.FullName;
                            if (!_editorTypes.ContainsKey(graphTypeFullName))
                            {
                                _editorTypes.Add(graphTypeFullName, type);
                                // Debug.Log($"Registered Graph Editor: {attr.GraphType} -> {type.Name}");
                            }
                        }
                    }
                }
            }
        }

        public static BaseGraphEditor CreateEditor(string graphType)
        {
            if (_editorTypes.TryGetValue(graphType, out Type type))
            {
                return Activator.CreateInstance(type) as BaseGraphEditor;
            }
            return null;
        }
    }
}